const path = require('path');
const fs = require('fs-extra');
const uuidv1 = require('uuid').v1;

class InitConfig {
  constructor() {
    const { PRO_ENV, PRO_TEMPLATE } = process.env;
    this.env = PRO_ENV || 'uat';
    this.PRO_TEMPLATE = PRO_TEMPLATE || 'fitment';
    this.initENV();
  }

  initENV() {
    const configPath = path.join(__dirname, `../env/${this.env}.json`); // 不同环境的CONFIG
    const sourcePath = path.join(__dirname, '../project.config.json'); // 开发小程序配置
    const extconfigPath = path.join(__dirname, `../src/${this.PRO_TEMPLATE}_ext.json`); // 授权小程序ext配置
    const extconfigPath_FIN = path.join(__dirname, `../src/ext.json`); // 模板授权小程序配置
    const extconfig = fs.readJSONSync(extconfigPath);
    const config = fs.readJSONSync(configPath);
    const sourceConfig = fs.readJSONSync(sourcePath);
    sourceConfig.appid = config.VUE_APP_APPID;
    extconfig.extAppid = config.EXT_APPID;
    fs.outputJsonSync(extconfigPath_FIN, extconfig, { spaces: 2 });
    fs.outputJsonSync(sourcePath, sourceConfig, { spaces: 2 });
    Object.assign(process.env, config);
    process.env.VUE_APP_BUILD_ID = uuidv1();
  }
  apply(compiler) {
    compiler.define['process.env'] = process.env;
  }
}

module.exports = InitConfig;
